import React, {useCallback, useEffect, useState} from 'react';
import classes from './index.module.scss'
import {Card, Image, Pagination} from "antd";
import Meta from "antd/es/card/Meta";
import {reqGetShopping, reqGetShoppingOrder} from "../../../api/frontDesk/frontDeskApi";
import history from "../../../utils/history";
import {useSelector} from "react-redux";

const Shopping = () => {



    const [shopList, setShopList] = useState([])
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(8);
    const [shopItem,setShopItem]=useState({})
    const {userAllInfo} = useSelector(state => state.persistedReducer.user)

    useEffect(() => {
        const getShopList = async () => {
            const result = await reqGetShopping()
            setShopList(result.data)
        }
        getShopList()
    }, [])


    const handlePageChange = (page) => {
        setCurrentPage(page);
    };

    // 处理分页器切换每页展示数据量事件（一般不需要用到）
    const handlePageSizeChange = (current, size) => {
        setPageSize(size);
    };

    // 根据分页器的current和pageSize属性获取对应页码的数据
    const getPageData = useCallback(() => {
        const start = (currentPage - 1) * pageSize;
        const end = start + pageSize;
        return shopList.slice(start, end);
    }, [shopList, currentPage, pageSize]);

    // 获取当前分页显示的数据
    const pageData = getPageData();


    //导航至购买界面
    const gotoBuy = async (item) => {
        await reqGetShoppingOrder({shopping_id: item.id, user_id: userAllInfo.id})
        history.push(`/buy-shopping/${item.id}`)
    }
    return (
        <>
            <div className={classes.Shopping}>
                {
                    pageData.map((item) =>
                        <Card
                            onClick={() => gotoBuy(item)}
                            key={item.id}
                            hoverable
                            style={{width: "21%", margin: "20px",height:350}}
                            cover={
                                <Image style={{width:'100%',height:250}}  alt="" src={item.cover}/>}
                        >
                            <Meta title={item.shop_name} description={item.price}/>
                        </Card>
                    )
                }
            </div>
            <div style={{width: '100%', height: 80, display: 'flex', justifyContent: 'center'}}>
                <Pagination
                    style={{position: 'absolute', bottom: 20,}}
                    total={shopList.length}
                    current={currentPage}
                    pageSize={pageSize}
                    showSizeChanger={false}
                    showQuickJumper
                    onChange={handlePageChange}
                    onShowSizeChange={handlePageSizeChange}
                />
            </div>
        </>
    );
};

export default Shopping;